// pages/order/order.js
const api = require('../../utils/api')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderList: [],
    tabs: ['全部', '待付款', '待发货', '待收货', '已完成'],
    currentTab: 0,
    loading: false,
    showReviewButtons: false,
    statusMap: {
      1: '待付款',
      2: '待发货',
      3: '待收货',
      4: '已完成',
      5: '已取消'
    },
    tabStatusMap: {
      'pending_payment': 1,
      'pending_delivery': 2,
      'delivered': 3,
      'completed': 4
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 检查登录状态
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }, 1500);
      return;
    }
    
    // 记录是否显示评价按钮
    if (options.showReviewButtons === 'true') {
      this.setData({
        showReviewButtons: true
      });
    }

    // 处理状态参数
    if (options.type === 'completed') {
      // 如果是从"我的购买历史"跳转过来，默认显示已完成订单
      this.setData({
        currentTab: 4 // 已完成对应索引
      });
    } else if (options.status && this.data.tabStatusMap[options.status] !== undefined) {
      this.setData({
        currentTab: this.data.tabStatusMap[options.status]
      });
    }
    
    this.loadOrders();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 检查登录状态
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }, 1500);
      return;
    }

    this.loadOrders();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadOrders();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 加载订单数据
  async loadOrders() {
    try {
      this.setData({ loading: true });
      const status = this.data.currentTab || undefined;
      const res = await api.getCustomerOrders(status);
      
      if (res.success) {
        const orderList = res.data.content || [];
        this.setData({ 
          orderList: orderList,
          loading: false
        });
      } else {
        throw new Error(res.message || '获取订单失败');
      }
    } catch (error) {
      console.error('加载订单失败:', error);
      wx.showToast({
        title: error.message || '加载订单失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  // 格式化订单数据
  formatOrders(orders) {
    return orders.map(order => ({
      ...order,
      statusText: this.data.statusMap[order.status] || '未知状态',
      createTimeText: this.formatTime(order.createTime)
    }));
  },

  // 格式化时间
  formatTime(timestamp) {
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  },

  // 切换标签
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ currentTab: index }, () => {
      this.loadOrders();
    });
  },

  // 查看订单详情
  viewOrderDetail(e) {
    const { orderNo } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/order/detail/detail?orderNo=${orderNo}`
    });
  },

  // 取消订单
  async cancelOrder(e) {
    const { orderNo } = e.currentTarget.dataset;
    try {
      wx.showModal({
        title: '提示',
        content: '确定要取消这个订单吗？',
        success: async (res) => {
          if (res.confirm) {
            const result = await api.cancelCustomerOrder(orderNo);
            if (result.success) {
              wx.showToast({
                title: '订单已取消',
                icon: 'success'
              });
              this.loadOrders();
            }
          }
        }
      });
    } catch (error) {
      wx.showToast({
        title: error.message || '取消订单失败',
        icon: 'none'
      });
    }
  },

  // 去支付
  goPay(e) {
    const { orderNo } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/order/payment/payment?orderNo=${orderNo}`
    });
  },

  // 确认收货
  async confirmReceipt(e) {
    const { orderNo } = e.currentTarget.dataset;
    try {
      wx.showModal({
        title: '提示',
        content: '确认已收到商品吗？',
        success: async (res) => {
          if (res.confirm) {
            const result = await api.confirmCustomerOrder(orderNo);
            if (result.success) {
              wx.showToast({
                title: '已确认收货',
                icon: 'success'
              });
              this.loadOrders();
            }
          }
        }
      });
    } catch (error) {
      wx.showToast({
        title: error.message || '确认收货失败',
        icon: 'none'
      });
    }
  },

  // 提醒发货
  remindDelivery(e) {
    wx.showToast({
      title: '已提醒商家发货',
      icon: 'success'
    });
  },

  // 去评价
  goToReview(e) {
    const { orderNo } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/review/review?orderNo=${orderNo}`,
      fail: (err) => {
        console.error('跳转到评价页面失败:', err);
        wx.showToast({
          title: '跳转评价页面失败',
          icon: 'none'
        });
      }
    });
  },

  // 删除订单
  async deleteOrder(e) {
    const { orderNo } = e.currentTarget.dataset;
    wx.showModal({
      title: '提示',
      content: '确定要删除这个订单吗？删除后不可恢复',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '处理中...' });
            const result = await api.deleteCustomerOrder(orderNo);
            wx.hideLoading();
            
            if (result.success) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              this.loadOrders();
            } else {
              throw new Error(result.message || '删除订单失败');
            }
          } catch (error) {
            wx.hideLoading();
            wx.showToast({
              title: error.message || '删除订单失败',
              icon: 'none',
              duration: 2000
            });
          }
        }
      }
    });
  },

  // 格式化价格
  formatPrice(price) {
    return '¥' + price.toFixed(2);
  }
})